import csv
import requests


def get_json(url, headers, params):
    resp = requests.get(url=url, headers=headers, params=params)
    return resp.json()


def parse_json(json_dict):
    replies = json_dict['data']['replies']
    replies_list = []

    for reply in replies:
        reply_dict = {}
        uname = reply['member']['uname']
        message = reply['content']['message']
        reply_dict['uname'] = uname
        reply_dict['message'] = message
        replies_list.append(reply_dict)
        print(reply_dict)

    return replies_list


def save_as_csv(replies):
    with open('replies.csv', 'a', newline='', encoding='utf-8-sig') as f:
        csv_writer = csv.DictWriter(f, fieldnames=['uname', 'message'])
        csv_writer.writerows(replies)




def main():
    url = 'https://api.bilibili.com/x/v2/reply/main'
    params = {
        "csrf": "2915d1475be6ebeca9be8528965961c2",
        "mode": "3",
        "oid": "998545357",
        "next": "2",  # next参数代表当前是第几页评论
        "plat": "1",
        "type": "1"
    }
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.43',

    }
    json_data = get_json(url, headers, params)
    replies = parse_json(json_data)
    save_as_csv(replies)


if __name__ == '__main__':
    main()
